# -*- coding: utf-8 -*-
__copyright__ = "Copyright (c) 2014-2017 Agora.io, Inc."


import flask

from src import RtcTokenBuilder2
from src import RtcTokenBuilder
from src import RtmTokenBuilder2
from src import RtmTokenBuilder
import time

bp = flask.Blueprint('token_app', __name__)


@bp.route('/v2/rtc/token', methods=('GET',))
def rtc_token_v2():
    print("rtc2 token")
    app = flask.current_app
    req = flask.request
    app.logger.info('recv gen-token req from {}'.format(req.remote_addr))

    query_info = req.args
    if 'channel_name' not in query_info:
        flask.abort(400)
    if 'uid' not in query_info:
        flask.abort(400)

    app_id = flask.current_app.config['APP_ID']
    app_certificate = flask.current_app.config['APP_CERTIFICATE']
    uid = query_info['uid']
    channel_name = query_info['channel_name']

    access_token2 = ''
    try:
        token_expiration_in_seconds = 3600
        privilege_expiration_in_seconds = 3600
        access_token2 = RtcTokenBuilder2.RtcTokenBuilder.build_token_with_uid(app_id, app_certificate, channel_name, uid, RtcTokenBuilder2.Role_Subscriber,
                                                 token_expiration_in_seconds, privilege_expiration_in_seconds)
        print("Token with int uid: {}".format(access_token2))
    except Exception as e:
        app.logger.info(repr(e))
        flask.abort(500)
    app.logger.info('token {}'.format(access_token2))
    return access_token2


@bp.route('/v1/rtm/token', methods=('GET',))
def rtm_token_v1():
    print("rtm1 token")
    app = flask.current_app
    req = flask.request
    app.logger.info('recv gen-token req from {}'.format(req.remote_addr))

    query_info = req.args
    if 'uid' not in query_info:
        flask.abort(400)
    

    app_id = flask.current_app.config['APP_ID']
    app_certificate = flask.current_app.config['APP_CERTIFICATE']
    uid = query_info['uid']

    access_token2 = ''
    try:
        expirationTimeInSeconds = 3600
        currentTimestamp = int(time.time())
        privilegeExpiredTs = currentTimestamp + expirationTimeInSeconds
        access_token2 = RtmTokenBuilder.RtmTokenBuilder.buildToken(app_id, app_certificate, uid, RtmTokenBuilder.Role_Rtm_User, privilegeExpiredTs)
    except Exception as e:
        app.logger.info(repr(e))
        flask.abort(500)
    app.logger.info('token {}'.format(access_token2))
    return access_token2